#!/usr/bin/env python
import argparse
from bin.connect import LDAP_LINK
from base import root_dir,check_ip,random_string,time_strap
import time
import sys

def help():
    code = "create_user need key uid_num,gid_num,cn,sn,ou,name.\
    delete_user need ser_id=name,ou_id=id,cn=False.\
    search_user just search user."
    print("""
    create_user need key uid_num,gid_num,cn,sn,ou,name.
    delete_user need ser_id=name,ou_id=id,cn=False.
    search_user just search user.
    """)
    return code

def print_hi(name):
    print(f'---------  Hi, {name} ------------')  # Press Ctrl+F8 to toggle the breakpoint.

def search(ldap_manager,range='custemer_filter',key=None,type=None,cn=None,all=None):
    if type == "uid":
        if all:
            code = ldap_manager.search(range="uid", cn=cn,type='ALL')
        else:
            code = ldap_manager.search(range="uid", cn=cn)
    else:
        if key:
            print('[INFO] search_return')
            infor = ldap_manager.search_return(range=range)
            return infor
        else:
            print('[INFO] search')
            code = ldap_manager.search(range=range)

    print(code)

def delete_user(ldap_manager,name,group):
    code = ldap_manager.delete_User(user_id=name,ou_id=group,cn=False)
    print(code)

def create_user(ldap_manager,uid_num,gid_num,cn,sn,ou,name):
    print('[INFO]  create_User(uid_num=%s,gid_num=%s, cn=%s, sn=%s, ou=%s, name=%s))' % (uid_num,gid_num,cn,sn,ou,name))
    code = ldap_manager.create_User(uid_num=uid_num, \
                                    gid_num=gid_num, cn=cn, sn=sn, ou=ou, \
                                    name=name)
    if code['result'] == 0:
        print('[INFO] Create %s success!' % name )
        return True
    else:
        print("[ERROR] Code:",code['result'])
        return False


def modify_user(key=None,uid=None,ou=None,new_cn=None,new_passwd=None):
    from ldap3 import MODIFY_REPLACE

    if key == "description":
        conn.modify('uid=%s,ou=%s,dc=zaq,dc=test' % (uid,ou),
                { 'description': [(MODIFY_REPLACE, ['%s' % new_cn ])] })
        print(conn.result)
        return conn.result

    elif key == "deleteUser":
        from bin.csv import  save_use_csv

        conn.modify('uid=%s,ou=%s,dc=zaq,dc=test' % (uid,ou) ,
                {'userPassword': [(MODIFY_REPLACE, ['%s' % new_passwd ])]  }  )
        print(conn.result)
        conn.modify('uid=%s,ou=%s,dc=zaq,dc=test' %(uid,ou),
                {'cn': [(MODIFY_REPLACE, ['%s' % new_cn])]  }  )
        print(conn.result)
        save_use_csv(dir=root_dir, key="deleteUser", username=uid, password=new_passwd,new_username=new_cn,ou=ou)
        return conn.result

    elif key == "modifyPasswd":
        time.sleep(0.2)
        conn.modify('uid=%s,ou=%s,dc=zaq,dc=test' % (uid,ou) ,
                {'userPassword': [(MODIFY_REPLACE, ['%s' % new_passwd ])]  }  )
        return conn.result
    else:
        print('[ERR] current can\'t support this CMD , in enter def modify_user() ')


if __name__ == '__main__':
    print_hi('openldap')
    section = 'openldap'

    ldap_manager = LDAP_LINK(section)

    # [main local test]
    conn = ldap_manager.conn

    # base_dn = 'cn=P7,ou=people'


    # new_passwd = 'test456'

    # conn.modify('uid=P7,ou=people,dc=zaq,dc=test',
    #             { 'description': [(MODIFY_REPLACE, ['new description'])] })

    # conn.modify('uid=P6,ou=shuoyao,dc=zaq,dc=test',
    #             {'userPassword': [(MODIFY_REPLACE, ['test567'])]  }  )

    # conn.modify('uid=P6,ou=shuoyao,dc=zaq,dc=test',
    #             {'cn': [(MODIFY_REPLACE, ['P6-out-user'])]  }  )

    print(conn.result)

    # [output check something]
    # ldap_manager.output()

    '''    
    ldap_manager = LDAP_LINK('openldap')
    search(ldap_manager)  # can to choice diff func() to run
    '''

    parser = argparse.ArgumentParser()

    parser.add_argument('-c', '--create', action='store_true',\
                        help="create user")
    parser.add_argument('-d', '--delete', action='store_true',\
                        help="delete user")
    parser.add_argument('-m', '--modify', action='store_true', \
                        help="modify user message")

    parser.add_argument('-s','--search', action='store_true',\
                        help="search_user")
    parser.add_argument('-u','--uid', dest='uid', action='append',\
                        help="input user uid")
    parser.add_argument('-gid', dest='gid', action='append',\
                        help="input user gid")
    parser.add_argument('-f','--find',dest='cn', action='append',\
                        help="input user cn re ")
    parser.add_argument('-n','--name',dest='name', action='append',\
                        help="input user name")
    parser.add_argument('-sn',dest='sn', action='append',\
                        help="input sn <User Tag>")
    parser.add_argument('-o','--ou',dest='ou', action='append',\
                        help="input user group")
    parser.add_argument('-g','--gid',dest='gid', action='append',\
                        help="input gid num")
    parser.add_argument('-e','--etc',dest='etc', action='append',\
                        help="etc test")

    parser.add_argument('--type',dest='type', action='append',\
                        help="choice diffrent run type")

    args = parser.parse_args()

    if args.create:
        if args.type[0] == 'excel':
            from bin.csv import get_dic_from_csv,save_use_csv
            user_dict = get_dic_from_csv(dir=root_dir,key='create')
            print('[DEBUG] ----core-----')
            if user_dict != None:
                infor = search(ldap_manager, range='custemer_filter', key="uid")
                max_v = 0
                for i in infor:
                    if int(i[0]) > max_v:
                        max_v = int(i[0])
                print(max_v)

                for key in user_dict.keys():
                    name = user_dict['%s' % key]['name*']
                    ou = user_dict['%s' % key]['ou']
                    cn = user_dict['%s' % key]['cn']
                    sn = user_dict['%s' % key]['sn*']
                    try:
                        mail = user_dict['%s' % key]['mail']
                    except:
                        mail = None
                    max_v += 1
                    uid_num = max_v
                    gid_num = uid_num
                    print('[DEBUG] Create Name: %s' % name)
                    time.sleep(0.2)
                    if create_user(ldap_manager, uid_num, gid_num, cn, sn, ou, name):
                        new_passwd = 'sy' + random_string()
                        code = modify_user(key="modifyPasswd", uid=name, ou=ou, new_passwd=new_passwd)
                        if mail:
                            ldap_manager.modify(key='mail',uid=name,ou=ou,new_mail=mail)
                        if code['result'] == 0:
                            pass
                        else:
                            print('[ERROR]',code.result)
                        code = save_use_csv(dir=root_dir, key="create", username=name, password=new_passwd,ou=ou,cn=cn)
                    else:
                        print('[ERROR] Create false!')
            else:
                print('[ERROR] False! ')
        else:
            uid_num = args.uid
            gid_num = args.gid
            cn = args.cn
            sn = args.sn
            ou = args.ou
            name = args.name
            create_user(ldap_manager,uid_num,gid_num,cn,sn,ou,name)
    elif args.delete:
        name = args.name[0]
        group = args.ou[0]
        delete_user(ldap_manager, name, group)
    elif args.modify:
        if args.type[0] == "deleteUser":
            uid = args.uid[0]
            ou = args.ou[0]
            new_passwd = 'sy' + random_string()
            print(new_passwd)

            new_cn='delete-' + time_strap() + '-' + uid
            print(new_cn)
            modify_user(key="deleteUser", uid=uid, ou=ou, new_cn=new_cn,new_passwd=new_passwd)
        else:
            print('please input other key')
    elif args.search:
        try:
            key = args.type[0]
            if key == "uid":
                cn = args.cn[0]
                try:
                    all = args.etc[0]
                except:
                    all = False

                if all:
                    search(ldap_manager, range='custemer_filter', type=key,cn=cn,all=all)
                else:
                    search(ldap_manager, range='custemer_filter', type=key,cn=cn)

            else:
                search(ldap_manager, range='custemer_filter',key=key)
        except:
            search(ldap_manager, range='custemer_filter',key=None)
    else:
        code = help()
